/**
 * 
 */
package com.gxt.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.gxt.enums.VideoStatusEnum;
import com.gxt.pojo.Bgm;
import com.gxt.pojo.Videos;
import com.gxt.service.BgmService;
import com.gxt.service.UserService;
import com.gxt.service.VideoService;
import com.gxt.utils.FetchVideoCover;
import com.gxt.utils.IMoocJSONResult;
import com.gxt.utils.MergeVideoMp3;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author JasonGuo
 * @Description:
 */
@RestController
@Api(value = "视频业务接口", tags = {"视频业务相关的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController{
	@Autowired
	private UserService userservice;
	
	@Autowired
	private BgmService bgmservice; 
	
	@Autowired
	private VideoService videoService; 
	
	@ApiOperation(value = "上传视频",notes = "上传视频的接口")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId",value = "用户Id",required = true,
			dataType = "String",paramType = "form"),

		@ApiImplicitParam(name = "bgmId",value = "背景音乐Id",required = false,
			dataType = "String",paramType = "form"),
		
		@ApiImplicitParam(name = "videoSeconds",value = "背景音乐播放长度",required = true,
			dataType = "double",paramType = "form"),
		
		@ApiImplicitParam(name = "videoWidth",value = "视频宽度",required = true,
			dataType = "int",paramType = "form"),
		
		@ApiImplicitParam(name = "videoHeight",value = "视频高度",required = true,
			dataType = "int",paramType = "form"),
		
		@ApiImplicitParam(name = "desc",value = "视频描述",required = false,
		dataType = "String",paramType = "form"),
	})

	@PostMapping(value = "/upload", headers="content-type=multipart/form-data")
	public IMoocJSONResult upload(String userId,
					String bgmId,double videoSeconds,
					int videoWidth,int videoHeight,
					String desc,
					@ApiParam(value = "短视频",required = true) MultipartFile file) throws Exception {
		
		if(StringUtils.isBlank(userId)) {
			return IMoocJSONResult.errorMsg("用户Id不能为空!");
		}
		
//		 文档保存命名空间
//		String fileSpace = "E:/gxt_videos";
		
//		 保存到数据库的相对路径
		String uploadPathDB = "/" + userId + "/video";
		String coverPathDB = "/" + userId + "/video";
		
		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		
//		文件上传的最终保存路径
		String finalVideoPath = "";
		try {
			if(file != null ) {
				String fileName = file.getOriginalFilename();
				//abc.mp4
				String fileNamePrefix = fileName.split("\\.")[0];
				
				if(StringUtils.isNotBlank(fileName)) {
//				
					finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
//				设置数据库保存的路径
					uploadPathDB += ("/" + fileName);
					coverPathDB += ("/") + fileNamePrefix + ".jpg";
					
//				作判断  如果父文件夹不存在则创建
					File outFile = new File(finalVideoPath);
					if(outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
//					创建父文件夹
						outFile.getParentFile().mkdirs();
					}
					
					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
					
					IOUtils.copy(inputStream, fileOutputStream);
//				考虑关闭输出流的情况
				}
			}else {
				return IMoocJSONResult.errorMsg("上传出错！");
			}
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return IMoocJSONResult.errorMsg("上传出错...");
		} finally {
			if(fileOutputStream!=null) {
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}
		
//		判断bgmId是否为空，如果不为空，
//		那就查询bgm的信息，并且合并视频，生产新的视频
		if(StringUtils.isNotBlank(bgmId)) {
//			进行搜索
			Bgm bgm = bgmservice.queryBgmById(bgmId);
			String mp3InputPath = FILE_SPACE + bgm.getPath();
			
			MergeVideoMp3 mergeVideoMp3 = new MergeVideoMp3(FFMPEG);
			
			String videoInputPath = finalVideoPath;
			String videoOutputName = UUID.randomUUID().toString() + ".mp4";
			uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName;
			
			finalVideoPath = FILE_SPACE + uploadPathDB;
			
			
			mergeVideoMp3.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
		}
		
		System.out.println(uploadPathDB);
		System.out.println(finalVideoPath);
//		视频mp3融合结束
//		对视频做截图操作
		// 获取视频信息。
				FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG);
				try {
					videoInfo.getCover(finalVideoPath, FILE_SPACE + coverPathDB);

				} catch (Exception e) {
					e.printStackTrace();
				}
		
		
//		保存成果视频到数据库
		Videos video = new Videos();
		video.setAudioId(bgmId);
		video.setUserId(userId);
		video.setVideoSeconds((float)videoSeconds);
		video.setVideoHeight(videoHeight);
		video.setVideoWidth(videoWidth);
		video.setVideoDesc(desc);
		video.setVideoPath(uploadPathDB);
		video.setCoverPath(coverPathDB);
		video.setStatus(VideoStatusEnum.SUCCESS.value);
		video.setCreateTime(new Date());
		
		String videoId = videoService.saveVideo(video);
//		return IMoocJSONResult.build(200,"OK","视频上传成功，融合mp3");
		return IMoocJSONResult.ok(videoId);
	}
	
	
	@ApiOperation(value = "上传封面",notes = "上传封面的接口")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId",value = "用户Id",required = true,
				dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "videoId",value = "视频主键Id",required = true,
			dataType = "String",paramType = "form")
	})

	@PostMapping(value = "/uploadCover", headers="content-type=multipart/form-data")
	public IMoocJSONResult uploadCover( String userId, String videoId,
					@ApiParam(value = "视频封面", required = true) MultipartFile file) throws Exception {
		
		if(StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) {
			return IMoocJSONResult.errorMsg("用户Id或视频主键Id不能为空!");
		}
		
//		 文档保存命名空间
//		String fileSpace = "E:/gxt_videos";
		
//		 保存到数据库的相对路径
		String uploadPathDB = "/" + userId + "/video";
		
		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		
//		文件上传的最终保存路径
		String finalCoverPath = "";
		try {
			if(file != null ) {
			
				
				String fileName = file.getOriginalFilename();
				
				if(StringUtils.isNotBlank(fileName)) {
//				
					finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
//				设置数据库保存的路径
					uploadPathDB += ("/" + fileName);
					
//				作判断  如果父文件夹不存在则创建
					File outFile = new File(finalCoverPath);
					if(outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
//					创建父文件夹
						outFile.getParentFile().mkdirs();
					}
					
					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
					
					IOUtils.copy(inputStream, fileOutputStream);
//				考虑关闭输出流的情况
				}
			}else {
				return IMoocJSONResult.errorMsg("上传出错！");
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
			return IMoocJSONResult.errorMsg("上传出错...");
		} finally {
			if(fileOutputStream!=null) {
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}
		
//		保存到数据库
		videoService.updateVideo(videoId, uploadPathDB);
		return IMoocJSONResult.ok("封面上传成功");
	}
}
